/**
 * @Author: easten
 * @Created: 2024-07-21 15:23:19
 * @Description: 测点管理
 *
 */
import { ApiDevice, ApiDeviceGroup } from "_common/api/iot";
import { ApiPoint } from "_common/api/iot/ApiPoint";
import { DrawerProps, TreeDataModel } from "_common/DataType";
import { IotDevice, IotDeviceGroup, IotPoint } from "_common/entity";
import { AxiosInstance } from "axios";
import React, { useState, useEffect, useRef } from "react";
import {
  Button,
  Drawer,
  Form,
  FormInstanceFunctions,
  Input,
  MessagePlugin,
  Select,
} from "tdesign-react";
import FormItem from "tdesign-react/es/form/FormItem";
type PointDrawerProps = DrawerProps & {
  axios: AxiosInstance;
  facility?: TreeDataModel;
};
const PointDrawer: React.FC<PointDrawerProps> = (props: PointDrawerProps) => {
  useEffect(() => {
    return () => {};
  }, []);
  const { open, facility, edit, onSuccess, value, axios } = props;
  const formRef = useRef<FormInstanceFunctions>();

  // 设备分组信息
  const [device, setDevice] = useState<IotDevice[]>([]);
  const [deviceFilter, setDeviceFilter] = useState<IotDevice[]>([]);

  // 定义产品类型
  const [groups, setGroups] = useState<IotDeviceGroup[]>([]);

  const apiPoint = new ApiPoint(axios);
  const apiDevice = new ApiDevice(axios);
  const apiGroup = new ApiDeviceGroup(axios);

  // 监听选中的设备分组
  const [form] = Form.useForm();
  const groupFormRef = Form.useWatch("group", form);

  useEffect(() => {
    if (groupFormRef) {
      setDeviceFilter(device.filter((item) => item?.dtCode == groupFormRef));
    }
  }, [groupFormRef]);

  useEffect(() => {
    getDeviceGroup();
    getMonitor();
    return () => {
      formRef.current?.reset();
    };
  }, [facility]);

  useEffect(() => {
    if (value && edit) {
      let data = {
        ...value,
      };
      formRef.current?.setFieldsValue(data);
    }
  }, [edit, value]);

  const handleClose = () => {
    onSuccess?.(false);
    formRef.current?.reset();
  };

  const getDeviceGroup = async () => {
    const response = await apiGroup.getDeviceGroupList();
    if (response && response.code == 200 && response.data) {
      setGroups(response.data);
    }
  };

  // 获取设备分组信息
  const getMonitor = async () => {
    const response = await apiDevice.getDeviceList();
    if (response && response.code == 200 && response.data) {
      console.log("facility:", facility);
      setDevice(response.data);
    }
  };

  // 新增设备
  const createMonitor = async (data: IotPoint) => {
    // 解构动态表单数据
    const response = await apiPoint.create({
      ...data,
      facilityId: facility?.value,
    });
    if (response && response.code == 200 && response.data) {
      MessagePlugin.success("新增成功");
      handleClose();
    }
  };
  // 更新设备
  const updateMonitor = async (data: IotPoint) => {
    const response = await apiPoint.update({
      ...data,
      facilityId: facility?.value,
      id: value?.id,
    });
    if (response && response.code == 200 && response.data) {
      MessagePlugin.success("更新成功");
      handleClose();
    }
  };

  return (
    <Drawer
      header={`${edit ? "编辑" : "添加"}测点`}
      footer={false}
      visible={open}
      sizeDraggable
      size="medium"
      onClose={handleClose}
    >
      <Form
        form={form}
        ref={formRef}
        labelWidth={100}
        onSubmit={async (data) => {
          // 是否校验通过
          if ((await formRef.current?.validateOnly()) == true) {
            edit
              ? updateMonitor(data.fields as IotPoint)
              : createMonitor(data.fields as IotPoint);
          }
        }}
      >
        <FormItem label="测点名称" rules={[{ required: true }]} name="name">
          <Input />
        </FormItem>
        <FormItem label="测点编号" rules={[{ required: true }]} name="code">
          <Input />
        </FormItem>
        {/*  <FormItem
          label="测点类型"
          rules={[{ required: true }]}
          name="monitorType"
        >
          <Select
            options={typeDict?.map((item) => {
              return { label: item.dictLabel, value: item.dictCode };
            })}
          />
        </FormItem> */}
        <FormItem
          label="测点位置"
          rules={[{ required: false }]}
          name="location"
        >
          <Input />
        </FormItem>
        <FormItem label="产品类型" rules={[{ required: true }]} name="group">
          <Select
            filterable
            options={groups?.map((item) => {
              return { label: item.groupName, value: item.groupCode };
            })}
          />
        </FormItem>
        <FormItem
          label="关联设备"
          rules={[{ required: true }]}
          name="deviceCode"
        >
          <Select
            filterable
            options={deviceFilter?.map((item) => {
              return { label: item.deviceName, value: item.deviceCode };
            })}
          />
        </FormItem>
        <FormItem className="float-right">
          <Button type="submit" theme="primary">
            提交
          </Button>
          <Button type="reset" theme="success" style={{ marginLeft: 12 }}>
            重置
          </Button>
        </FormItem>
      </Form>
    </Drawer>
  );
};
export default PointDrawer;
